package com.sky.configuration;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {
    /**
     * 订单交换机
     */
    public static final String ORDER_EXCHANGE = "order_exchange";
    /**
     * 订单队列
     */
    public static final String ORDER_QUEUE = "order_queue";
    /**
     * 订单路由键
     */
    public static final String ORDER_ROUTING = "order_routing";
    /**
     * 死信交换机
     */
    public static final String ORDER_DEAD_EXCHANGE = "order_dead_exchange";
    /**
     * 死信队列
     */
    public static final String ORDER_DEAD_QUEUE = "order_dead_queue";
    /**
     * 死信路由键
     */
    public static final String ORDER_DEAD_ROUTING = "order_dead_routing";

    /**
     * 订单交换机
     */
    @Bean("orderExchange")
    public Exchange getOrderExchange() {
        return new DirectExchange(ORDER_EXCHANGE);
    }

    /**
     * 订单队列
     */
    @Bean("orderQueue")
    public Queue getOrderQueue() {
        Map<String, Object> map = new HashMap<>(3);
        map.put("x-dead-letter-exchange", ORDER_DEAD_EXCHANGE);//死信交换机
        map.put("x-dead-letter-routing-key", ORDER_DEAD_ROUTING);//死信路由键
        map.put("x-message-ttl", 1000 * 60 * 15);//队列过期时间
        return QueueBuilder
                .durable(ORDER_QUEUE)
                .withArguments(map)
                .build();
    }

    /**
     * 将订单交换机与订单队列绑定
     */
    @Bean
    Binding orderExchangeBindingOrder(@Qualifier("orderExchange") Exchange exchange,
                                      @Qualifier("orderQueue") Queue queue) {
        return BindingBuilder.bind(queue).to(exchange).with(ORDER_ROUTING).noargs();
    }

    /**
     * 死信交换机
     */
    @Bean("orderDeadExchange")
    public Exchange getOrderDeadExchange() {
        return new DirectExchange(ORDER_DEAD_EXCHANGE);
    }

    /**
     * 死信队列
     */
    @Bean("orderDeadQueue")
    public Queue getOrderDeadQueue() {
        return new Queue(
                ORDER_DEAD_QUEUE,//队列名
                true,//是否持久化
                false,//是否具有排他性，只在首次声明时可见，不允许其他用户访问，连接断开时自动删除
                false,//是否自动删除，经历过至少一次连接后，所有消费者都断开了连接，此队列会自动删除
                null
        );
    }

    /**
     * 将死信交换机与死信队列绑定
     */
    @Bean
    Binding deadExchangeBindingDeadQueue(@Qualifier("orderDeadExchange") Exchange exchange,
                                         @Qualifier("orderDeadQueue") Queue queue) {
        return BindingBuilder.bind(queue).to(exchange).with(ORDER_DEAD_ROUTING).noargs();
    }
}
